<?php


namespace app\middleware\v1;

use app\model\v1\Auth;
use app\model\v1\Role;
use app\service\v1\ManagerToken;
use think\exception\HttpException;
use think\Request;

// 管理员操作方法中间件
class ManagerAction
{
    /**
     * @param Request $request
     * @param \Closure $next
     * @return mixed
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function handle(Request $request, \Closure $next)
    {
        // 如果不是超管 则验证操作权限
        if (!ManagerToken::isSuperManager()) {
            // 1、获取当前管理员角色id
            $roleId = ManagerToken::getCurrentRoleId();
            // 2、根据角色id 查询角色拥有的权限ids
            $roleInfo = (new Role)->info($roleId);
            $authIds = $roleInfo->auth_ids;
            // 3、根据权限ids 查询权限对应的操作方法
            $actions = (new Auth)->whereIn('id', $authIds)->column('actions');
            // 获取的操作方法数组 ===> ['add,getList', 'add']
            // 先将数组转为字符串 ===> 'add,getList,add'
            // 再将字符串转为数组 ===> ['add', 'getList', 'add']
            $actions = explode(',', implode(',', $actions));
            // 4、操作方法与当前访问的方法比对
            if (empty($actions) || !in_array($request->action(), $actions)) {
                throw new HttpException(403, '暂无操作权限');
            }
        }
        return $next($request);
    }
}